package com.guoqi.clickevent

import android.annotation.SuppressLint
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.graphics.Path
import android.os.Build
import android.os.Handler
import android.os.Message
import android.provider.Settings
import android.support.v7.app.AlertDialog
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import com.guoqi.clickevent.float_view.FloatBallView
import com.guoqi.clickevent.float_view.FloatWindowManager
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : BaseActivity() {
    private var dialog: AlertDialog? = null
    private var delay = 3000L
    private var speed = 200L
    private var direction = Gravity.LEFT
    private var screenDirection = 0// 1竖屏 0横屏
    private var isStart = false
    private var path = Path()
    var mView: PathView? = null

    var repeatHandler = @SuppressLint("HandlerLeak")
    object : Handler() {
        override fun handleMessage(msg: Message?) {
            if (isStart && floatWindowManager.floatView != null && !(floatWindowManager.floatView as FloatBallView).isDragged) {
                ClickService.dispatchGestureMove(path, speed)
                sendEmptyMessageDelayed(0, delay)
            }
        }
    }

    override fun getLayoutResId(): Int {
        return R.layout.activity_main
    }

    override fun initData() {
        floatWindowType = FloatWindowManager.FW_TYPE_ALERT_WINDOW
    }

    override fun initView() {
        mView = PathView(this)

        ACache.get(this).getAsObject("direction")?.let {
            direction = it.toString().toInt()
            when (it) {
                Gravity.LEFT -> et_direction.setText("左滑")
                Gravity.RIGHT -> et_direction.setText("右滑")
                Gravity.TOP -> et_direction.setText("上滑")
                Gravity.BOTTOM -> et_direction.setText("下滑")
            }
        }
        ACache.get(this).getAsObject("delay")?.let {
            delay = it.toString().toLong()
            et_delay.setText(delay.toString())
        }
        ACache.get(this).getAsObject("speed")?.let {
            speed = it.toString().toLong()
            et_speed.setText(speed.toString())
        }
        ACache.get(this).getAsObject("screenDirection")?.let {
            screenDirection = it.toString().toInt()
            if (screenDirection == 1) {
                et_screen.setText("竖屏")
            } else {
                et_screen.setText("横屏")
            }
        }

        //禁用输入
        et_direction.isCursorVisible = false
        et_direction.setOnClickListener {
            (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(et_direction.windowToken, 0)
            showDirectionAlertDialog()
        }
        et_screen.isCursorVisible = false
        et_screen.setOnClickListener {
            (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(et_screen.windowToken, 0)
            showDirectionAlertDialog2()
        }
        setMyTouch(object : MyTouchListener {
            override fun onDragged() {
                repeatHandler.sendEmptyMessageDelayed(0, delay)
            }

            override fun onTouch() {
                repeatHandler.removeCallbacksAndMessages(0)
            }

        })
        btn_fling.setOnClickListener {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                Toast.makeText(this@MainActivity, "7.0及以上才可使用", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if (isStart) {
                btn_fling.text = "开启自动滑屏"
                isStart = false
                fl_view.removeAllViews()
                fl_view.visibility = View.GONE
                path.reset()
                //关闭悬浮框
                //floatWindowManager.dismissFloatWindow()
            } else {
                btn_fling.text = "停止自动滑屏"
                isStart = true
                checkPermissionAndShow()
                //设置方向
                when (direction) {
                    Gravity.LEFT -> {
                        //竖屏
                        if (screenDirection == 1) {
                            path.moveTo(800f, 500f)
                            path.lineTo(20f, 500f)
                        } else {
                            path.moveTo(1300f, 500f)
                            path.lineTo(20f, 500f)
                        }
                    }
                    Gravity.RIGHT -> {
                        if (screenDirection == 1) {
                            path.moveTo(20f, 500f)
                            path.lineTo(800f, 500f)
                        } else {
                            path.moveTo(20f, 500f)
                            path.lineTo(1300f, 500f)
                        }
                    }
                    Gravity.TOP -> {
                        path.moveTo(300f, 200f)
                        path.lineTo(300f, 1200f)
                    }
                    Gravity.BOTTOM -> {
                        path.moveTo(300f, 1200f)
                        path.lineTo(300f, 200f)
                    }
                }
                //设置延迟
                if (et_delay.text.isNotEmpty()) {
                    delay = et_delay.text.toString().toLong()
                }

                //设置滑动速度
                if (et_speed.text.isNotEmpty()) {
                    speed = et_speed.text.toString().toLong()
                }
                repeatHandler.sendEmptyMessageDelayed(0, 800)
                Toast.makeText(this, "开始执行", Toast.LENGTH_SHORT).show()

                fl_view.addView(mView)
                fl_view.visibility = View.VISIBLE
                //保存参数
                ACache.get(this).put("direction", direction)
                ACache.get(this).put("delay", delay)
                ACache.get(this).put("speed", speed)
            }
        }
    }

    private fun showDirectionAlertDialog2() {
        val items = arrayOf("横屏", "竖屏")
        val index = screenDirection
        AlertDialog.Builder(this)
                .setTitle("选择屏幕方向")
                .setSingleChoiceItems(items, index) { d, i ->
                    et_screen.setText(items[i])
                    screenDirection = i
                    ACache.get(this).put("screenDirection", i)
                    d.dismiss()
                }
                .create().show()
    }

    private fun showDirectionAlertDialog() {
        val items = arrayOf("左滑", "右滑", "上滑", "下滑")
        var index = 0
        when (direction) {
            Gravity.LEFT -> index = 0
            Gravity.RIGHT -> index = 1
            Gravity.TOP -> index = 2
            Gravity.BOTTOM -> index = 3
        }
        AlertDialog.Builder(this)
                .setTitle("选择模拟滑动方向")
                .setSingleChoiceItems(items, index) { d, i ->
                    et_direction.setText(items[i])
                    when (i) {
                        0 -> direction = Gravity.LEFT
                        1 -> direction = Gravity.RIGHT
                        2 -> direction = Gravity.TOP
                        3 -> direction = Gravity.BOTTOM
                    }
                    d.dismiss()
                }
                .create().show()
    }

    override fun onResume() {
        super.onResume()
        if (ClickService.isRunning) {
            dialog?.dismiss()
        } else {
            showOpenAccessibilityServiceDialog()
        }
    }

    /** 显示未开启辅助服务的对话框 */
    private fun showOpenAccessibilityServiceDialog() {
        if (dialog != null && dialog!!.isShowing) {
            return
        }
        val view = layoutInflater.inflate(R.layout.dialog_tips_layout, null)
        view.setOnClickListener { openAccessibilityServiceSettings() }
        val builder = AlertDialog.Builder(this)
        builder.setTitle("需要开启辅助服务正常使用")
        builder.setView(view)
        builder.setPositiveButton("打开辅助服务") { dialog, which -> openAccessibilityServiceSettings() }
        dialog = builder.show()
    }

    /** 打开辅助服务的设置 */
    private fun openAccessibilityServiceSettings() {
        try {
            val intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
            startActivity(intent)
            Toast.makeText(this, "找到 [点击辅助] ,然后开启服务", Toast.LENGTH_LONG).show()
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    override fun onBackPressed() {
        if (isStart) {
            btn_fling.performClick()
            Toast.makeText(this@MainActivity, "已停止", Toast.LENGTH_SHORT).show()
        } else {
            super.onBackPressed()
        }
    }


    override fun onFloatWindowClick() {
        btn_fling.performClick()
    }

    override fun onDestroy() {
        super.onDestroy()
        isStart = false
        repeatHandler.removeCallbacksAndMessages(0)
    }

    /**
     * 应用是否在后台
     */
    fun isBackground(context: Context): Boolean {
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val appProcesses = activityManager.runningAppProcesses
        for (appProcess in appProcesses) {
            if (appProcess.processName == context.packageName) {
                if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
                    Log.e("后台", appProcess.processName)
                    return true
                } else {
                    Log.e("前台", appProcess.processName)
                    return false
                }
            }
        }
        return false
    }


}
